import { useContext, useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { AppContext } from "../../Context/AppContext";

export default function Show() {
    const {id} = useParams();
    const [post, setPost] = useState(null);
    const {user,token} = useContext(AppContext)
    const navigate = useNavigate();
    const getPost = async () => {
        const res = await fetch(`/api/posts/${id}`);
        const data = await res.json();
       if(res.ok){
        setPost(data.data);
       }
    }
    useEffect(() => {
        getPost();
    }, [id]);

    const handleDelete = async (e) => {
        e.preventDefault();
        const res = await fetch(`/api/posts/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
            // const data = await res.json();
            if(res.ok){
                alert('删除成功');
                navigate('/')
            }
    }
    return (
        <>
        {post?
    <div className="mb-4 p-4 border border-gray-300 rounded-md">
      <div className="mb-2 flex items-start justify-between">
        <div>
          <h2 className="font-bold text-lg">{post.title}</h2>
          <small>{new Date(post.created_at).toLocaleTimeString()}</small>
          <small>{'作者：'+post.user.name}</small>
        </div>
      </div>
      <p>{post.body}</p>
    {user && user.id === post.user.id&& <div className="flex items-center justify-end gap-4">
        <Link to={`/posts/${post.id}/edit`} className="bg-green-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">编辑</Link>
        <form onSubmit={handleDelete}>
            <button className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">删除</button>
        </form>
      </div>}
       </div>:<div className="title">文章加载中...</div>}
        </>
    )
}